package app

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/gorilla/mux"
)

// Route 根据url进行路由的数据结构体
type Route struct {
	Name        string
	Method      string
	Pattern     string
	HandlerFunc http.HandlerFunc
}

// Routes 一个路由链接的序列
type Routes []Route

// Service 方便和数据库端
var Service *NewService

// NewRouter 创建新的Router
func NewRouter(s *NewService) *mux.Router {
	Service = s
	router := mux.NewRouter().StrictSlash(true)
	for _, route := range routes {
		var handler http.Handler
		handler = route.HandlerFunc
		handler = Logger(handler, route.Name)

		router.
			Methods(route.Method).
			Path(route.Pattern).
			Name(route.Name).
			Handler(handler)
	}

	return router
}

// Index 首页请求，用于测试
func Index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello World!")
}

var routes = Routes{
	//一个用于测试的Route
	Route{
		"Index",
		"GET",
		"/",
		Index,
	},
	//用户相关的url
	Route{
		"URLLogin",
		strings.ToUpper("Post"),
		"/User/Login",
		URLLogin,
	},
	Route{
		"GetUserInfo",
		strings.ToUpper("Get"),
		"/User/{UserId}",
		URLGetUserInfo,
	},
	Route{
		"Signup",
		strings.ToUpper("Post"),
		"/User/Signup",
		URLSignup,
	},
	//一次性事件相关
	Route{
		"AddOnetime",
		strings.ToUpper("Post"),
		"/Onetime/add",
		URLAddOnetime,
	},
	Route{
		"DeleteOnetime",
		strings.ToUpper("Delete"),
		"/Onetime/{OnetimeID}",
		URLDeleteOnetime,
	},
	Route{
		"GetOnetime",
		strings.ToUpper("Get"),
		"/Onetime/{UserID}",
		URLGetOnetimeByID,
	},
	Route{
		"GetOnetimeSpecial",
		strings.ToUpper("Get"),
		"/Onetime/{UserID}/{Year}/{Month}/{Day}",
		URLGetSpecialOnetime,
	},
	//日常事件相关
	Route{
		"AddDaily",
		strings.ToUpper("Post"),
		"/Daily/add",
		URLAddDaily,
	},
	Route{
		"DeleteDaily",
		strings.ToUpper("Delete"),
		"/Daily/{DailyID}",
		URLDeleteDaily,
	},
	Route{
		"GetDaily",
		strings.ToUpper("Get"),
		"/Daily/{UserID}",
		URLGetDailyByID,
	},
	//周常事件相关
	Route{
		"AddWeekly",
		strings.ToUpper("Post"),
		"/Weekly/add",
		URLAddWeekly,
	},
	Route{
		"DeleteWeekly",
		strings.ToUpper("Delete"),
		"/Weekly/{WeeklyID}",
		URLDeleteWeekly,
	},
	Route{
		"GetWeekly",
		strings.ToUpper("Get"),
		"/Weekly/{UserID}",
		URLGetWeeklyByID,
	},
}
